package cn.finder.datatunnel.protocol;

import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import org.apache.log4j.Logger;

import cn.finder.datatunnel.DTConfig;
import cn.finder.datatunnel.ProcessorRunnable;
import cn.finder.datatunnel.processor.Processor;
import cn.finder.datatunnel.processor.UdpDataChannel;

public class Udp implements Protocol{

	private static Logger logger = Logger.getLogger(Udp.class);

	private static boolean looper = true;
	private DatagramSocket datagramSocket = null;
	//private Processor processor;
	
	private Class<? extends Processor> processorClass;
	public void setProcessorClass(Class<? extends Processor> processorClass){
		this.processorClass=processorClass;
	}
	
	public void start() throws Exception {
		
		try{
			datagramSocket=new DatagramSocket(Integer.parseInt(DTConfig.dt_client_listen_port));
		}
		catch(BindException be){
			/*boolean isBound = datagramSocket.isBound();
			if (isBound) {
				logger.debug("====socket listening port:"
						+ datagramSocket.getLocalPort());
			} else {
				logger.debug("====binding port:" + datagramSocket.getLocalPort()
						+ "failure");
				return ;
			}*/
			logger.debug("====binding port:" + DTConfig.dt_client_listen_port
					+ "failure details:"+be.getMessage());
			return ;
		}
		
		
		System.out.println("====udp service on :" + DTConfig.dt_client_listen_port
				+ " started... "); //启动状态一定要显示
	
		
		
		while (looper) {
			
			try {
				UdpDataChannel udpDataChannel=new UdpDataChannel();
				udpDataChannel.setChannel(datagramSocket);
				Processor processor=(Processor)processorClass.newInstance();
				processor.setDataChannel(udpDataChannel);
				
				
				
				Integer readdata_size=Integer.valueOf(DTConfig.dt_client_readdata_size);
				byte[] b=new byte[readdata_size.intValue()];
				
				DatagramPacket dataPacket = new DatagramPacket(b, b.length);
				
				udpDataChannel.getChannel().receive(dataPacket); //等待读取 阻塞线程   t.join 可以不需要
				udpDataChannel.setDatagramPacket(dataPacket);
				
			    InetAddress inetAddress=dataPacket.getAddress();
			    String clientAddr=inetAddress.getHostAddress();
				logger.debug("===客户端 ["+clientAddr+"] 连接...");
				
				
				Thread t=new Thread(new ProcessorRunnable(processor));
				
				t.start();
			//	t.join();
				logger.debug("读取下一条数据...");

			} catch (Exception e) {
				logger.error(e);
			}
			
		}
		//程序结束关闭 套接字
		datagramSocket.close();
		datagramSocket.disconnect();
		
	}

	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

	public void destory() {
		// TODO Auto-generated method stub
		
	}

	/*public Processor getProcessor() {
		return processor;
	}

	public void setProcessor(Processor processor) {
		this.processor = processor;
	}*/

	public DatagramSocket getDatagramSocket() {
		return datagramSocket;
	}

	
	
}
